package com.kim.common.resp;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.Writer;

/**
 * 统一返回对象
 * @param <T>
 */
@Slf4j
@Data
public class Result<T> {
	/**
	 * 状态值
	 */
	private boolean status;
	/**
	 * 返回码
	 */
	private int code;
	
	/**
	 * 信息
	 */
	private String msg;
	
	/**
	 * 数据
	 */
	private T result;

	/**
	 *  成功时候的调用
	 * */
	public static  <T> Result<T> success(T result){
		return new Result<T>(true,CodeMsg.SUCCESS, result);
	}

	public static  <T> Result<T> success(String msg, T result){
		return new Result<T>(true,new CodeMsg(0, msg), result);
	}

	public static  <T> Result<T> success(CodeMsg msg, T result){
		return new Result<T>(true,msg, result);
	}
	
	/**
	 *  失败时候的调用
	 * */
	public static  <T> Result<T> error(CodeMsg codeMsg){
		return new Result<T>(false,codeMsg);
	}

	public static  <T> Result<T> error(int code, String msg){
		return new Result<T>(false,code,msg);
	}

	public Result(){}

	public Result(T result) {
		this.result = result;
	}

	public Result(Boolean flag,CodeMsg codeMsg, T result) {
		this.status = flag;
		this.result = result;
		if(codeMsg != null) {
			this.code = codeMsg.getCode();
			this.msg = codeMsg.getMsg();
		}
	}
	
	public Result(Boolean flag,int code, String msg) {
		this.status = flag;
		this.code = code;
		this.msg = msg;
	}
	
	public Result(Boolean flag,CodeMsg codeMsg) {
		this.status = flag;
		if(codeMsg != null) {
			this.code = codeMsg.getCode();
			this.msg = codeMsg.getMsg();
		}
	}


	/**
	 * 通过流写到前端
	 *
	 * @param objectMapper 对象序列化
	 * @param response
	 * @param result
	 * @throws IOException
	 */
	public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, Result<Object> result) {
		response.setStatus(HttpStatus.OK.value());
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.setCharacterEncoding("UTF-8");
		try (
				Writer writer = response.getWriter();
		) {
			writer.write(objectMapper.writeValueAsString(result));
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("error class:{}  mes: {}", e.getClass().getName(), e.getMessage());
		}
	}
}
